//
//  MCReceivedHongBaoCollectionViewCell.m
//  XDYL
//
//  Created by MC on 2018/3/20.
//  Copyright © 2018年 TLYL01. All rights reserved.
//

#import "MCReceivedHongBaoCollectionViewCell.h"
#import "MCReceivedHongBaoHeaderView.h"
#import <MJRefresh/MJRefresh.h>
#import "MCReceivedHongBaoTableViewCell.h"
#import "MCReceivedRecordListModel.h"
#import "MCReceivedRecordTotalModel.h"
#import "MCHongBaoRecordProperty.h"

@interface MCReceivedHongBaoCollectionViewCell()
<
UITableViewDelegate,
UITableViewDataSource
>
typedef void(^Compeletion)(BOOL result, NSDictionary *data );

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray * dataMarray;
@property(nonatomic, strong)MCReceivedHongBaoHeaderView *headerView;

@property(nonatomic, strong)MCReceivedRecordListModel * receivedRecordListModel;
@property(nonatomic, strong)MCReceivedRecordTotalModel * receivedRecordTotalModel;

@property(nonatomic, strong) NSString * statTime1;
@property(nonatomic, strong) NSString * endTime1;
@property(nonatomic, strong) NSString * CurrentPageIndex1;
@property(nonatomic, strong) NSString * CurrentPageSize1;
@property(nonatomic, assign) BOOL IsHistory1;

@property(nonatomic, strong)ExceptionView * exceptionView;


@end


@implementation MCReceivedHongBaoCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        [self initView];
    }
    return self;
}


- (void)initView{
    
    self.backgroundColor=RGB(231,231,231);
    
    [self setProperty];
    
    [self createUI];
    
    [self refreashData];
    
}

- (void)refreashReceivedHongBaoProperty{
    
    MCReceivedHBRecordProperty * ReceivedProperty = [MCReceivedHBRecordProperty sharedMCReceivedHBRecordProperty];
    
    self.statTime1=ReceivedProperty.statTime;
    self.endTime1=ReceivedProperty.endTime;
    self.CurrentPageIndex1=ReceivedProperty.CurrentPageIndex;
    self.CurrentPageSize1=ReceivedProperty.CurrentPageSize;
    self.IsHistory1 =ReceivedProperty.IsHistory;
    
}

#pragma mark==================setProperty======================
-(void)setProperty{
    
    self.backgroundColor=RGB(231, 231, 231);
    _dataMarray=[[NSMutableArray alloc]init];
    [self refreashReceivedHongBaoProperty];
    
}
-(MCReceivedHongBaoHeaderView *)headerView{
    if (!_headerView) {
        _headerView=[[MCReceivedHongBaoHeaderView alloc]init];
//        _headerView.delegate=self;
        _headerView.frame=CGRectMake(0, 0, G_SCREENWIDTH, [MCReceivedHongBaoHeaderView computeHeight:nil]);
    }
    return _headerView;
}

#pragma mark==================createUI======================
-(void)createUI{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.layer.cornerRadius=5;
    _tableView.clipsToBounds=YES;
    _tableView.tableHeaderView=self.headerView;
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreashData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(15);
        make.left.equalTo(self.mas_left).offset(10);
        make.right.equalTo(self.mas_right).offset(-10);
        make.bottom.equalTo(self.mas_bottom).offset(5);
    }];
    
}

#pragma mark-下拉刷新
- (void)refreashData{
    __weak __typeof__ (self) wself = self;

    [self.dataMarray removeAllObjects];
    NSDictionary * dic=@{
                         @"BeginTime":self.statTime1,//开始时间
                         @"EndTime":self.endTime1,//结束时间
                         @"IsHistory":[NSNumber numberWithBool:self.IsHistory1],
                         @"CurrentPageIndex":self.CurrentPageIndex1,
                         @"CurrentPageSize":self.CurrentPageSize1
                         };
    
    MCReceivedRecordTotalModel * receivedRecordTotalModel = [[MCReceivedRecordTotalModel alloc]initWithDic:dic];
    [receivedRecordTotalModel refreashDataAndShow];
    self.receivedRecordTotalModel = receivedRecordTotalModel;
    
    receivedRecordTotalModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        wself.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
        wself.exceptionView.heightH=G_SCREENHEIGHT-64-40;
        wself.exceptionView.actionColor=RGB(255,69,69);
        ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
            [wself.exceptionView dismiss];
            wself.exceptionView = nil;
            [wself refreashData];
        }];
        [wself.exceptionView addAction:action];
        [wself.exceptionView showInView:self.tableView];
    };
    
    receivedRecordTotalModel.callBackSuccessBlock = ^(id manager) {

        [wself setHeaderData:manager];
    };
    
}

-(void)loadMoreData{
    
    _CurrentPageIndex1=[NSString stringWithFormat:@"%d",[_CurrentPageIndex1 intValue]+1];
    [BKIndicationView showInView:self];
    __weak __typeof__ (self) wself = self;
    [self loadData:^(BOOL result, NSDictionary *data) {
        [wself.tableView.mj_footer endRefreshing];
        [wself.tableView.mj_header endRefreshing];
        if (result) {
            [wself setData:data];
        }else{
            [SVProgressHUD showErrorWithStatus:@"加载失败"];
            wself.CurrentPageIndex1=[NSString stringWithFormat:@"%d",[_CurrentPageIndex1 intValue]-1];
        }
    }];
    
}


#pragma mark==================loadData======================
-(void)loadData:(Compeletion)compeletion{
    
    NSDictionary * dic=@{
                         @"BeginTime":self.statTime1,//开始时间
                         @"EndTime":self.endTime1,//结束时间
                         @"IsHistory":[NSNumber numberWithBool:self.IsHistory1],
                         @"CurrentPageIndex":self.CurrentPageIndex1,
                         @"CurrentPageSize":self.CurrentPageSize1
                         };

    MCReceivedRecordListModel * receivedRecordListModel = [[MCReceivedRecordListModel alloc]initWithDic:dic];
    [receivedRecordListModel refreashDataAndShow];
    self.receivedRecordListModel = receivedRecordListModel;
    
    receivedRecordListModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        compeletion(NO,nil);
    };
    
    receivedRecordListModel.callBackSuccessBlock = ^(id manager) {
        compeletion(YES,manager);
    };
    
}

-(void)setHeaderData:(NSDictionary *)dic{
    
    MCReceivedRecordTotalModel * model = [MCReceivedRecordTotalModel mj_objectWithKeyValues:dic];
    self.headerView.dataSource=model;
    
    [self.exceptionView dismiss];
    self.exceptionView = nil;
    self.tableView.mj_footer.hidden=NO;
    self.tableView.mj_header.hidden=NO;
    [BKIndicationView showInView:self];
    __weak __typeof__ (self) wself = self;
    _CurrentPageIndex1=@"1";
    
    [self loadData:^(BOOL result, NSDictionary *data) {
        
        [wself.tableView.mj_footer endRefreshing];
        [wself.tableView.mj_header endRefreshing];
        if (result) {
            
            [wself setData:data];
            
        }else{
            
            wself.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
            wself.exceptionView.heightH=G_SCREENHEIGHT-64-40;
            wself.exceptionView.actionColor=RGB(255,69,69);
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
                [wself.exceptionView dismiss];
                wself.exceptionView = nil;
                [wself refreashData];
            }];
            [wself.exceptionView addAction:action];
            [wself.exceptionView showInView:self.tableView];
            
        }
    }];
    
}

-(void)setData:(NSDictionary *)dic{
    

    NSDictionary * ReceivedRecords = dic[@"ReceivedRecords"];
    MCReceivedRecordsModel * model = [MCReceivedRecordsModel mj_objectWithKeyValues:ReceivedRecords];
    [self.dataMarray addObjectsFromArray:model.Records];
    
    if (self.dataMarray.count<1) {
        self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoData];
        self.exceptionView.heightH=G_SCREENHEIGHT-64-40;
        [self.exceptionView showInView:self.tableView];
        return;
    }
    if ( (model.Records.count%15!=0) || (model.Records.count==0) ) {
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.hidden=YES;
    }
    [self.tableView reloadData];
}

#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataMarray.count;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return [MCReceivedHongBaoHeaderView computeHeight:nil];
//}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    return nil;
//}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [MCReceivedHongBaoTableViewCell computeHeight:nil];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *reuseIdentifier =[NSString stringWithFormat:@"MCReceivedHongBaoTableViewCell-%ld-%ld",(long)indexPath.section,(long)indexPath.row];
    MCReceivedHongBaoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
         cell = [[MCReceivedHongBaoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if (self.dataMarray.count>0) {
        cell.dataSource=self.dataMarray[indexPath.row];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_dataMarray.count>0) {
        MCRecordsModel * model = [_dataMarray objectAtIndex:indexPath.row];
        NSString * Sysid =model.SysId;
        if (self.goToDetailReceivedHongBaoBlock) {
            self.goToDetailReceivedHongBaoBlock(Sysid);
        }
    }
    
    
}




/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


